package io.guanghe.modules.sys.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

import io.guanghe.common.utils.FileUtils;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.guanghe.modules.sys.entity.SysFileEntity;
import io.guanghe.modules.sys.service.SysFileService;
import io.guanghe.common.utils.PageUtils;
import io.guanghe.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author guanghe
 * @email 18903378092@163.com
 * @date 2021-12-27 11:03:56
 */
@RestController
@RequestMapping("sys/file")
public class SysFileController {
    @Autowired
    private SysFileService fileService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("sys:file:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = fileService.queryPage(params);

        return R.ok().put("page", page);
    }

    //查看图片
    @RequestMapping("/view/{id}")
    public void view(@PathVariable("id") Long id, HttpServletResponse httpServletResponse) {
        SysFileEntity file = fileService.getById(id);
        try(FileChannel channel = new FileInputStream(new File(file.getFilePath())).getChannel()) {
            //输出流不能使用AutoCloseable，否则catch块中无法输出错误信息到前台
            OutputStream os = httpServletResponse.getOutputStream();
            httpServletResponse.setContentType("image/png");
            ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
            int len;
            while((len = channel.  read(byteBuffer)) != -1) {
                os.write(byteBuffer.array(), 0, len);
                //重置读指针
                byteBuffer.clear();
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                httpServletResponse.sendError(-1, e.getMessage());
            } catch (Exception es) {
                es.printStackTrace();
            }
        }
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("sys:file:info")
    public R info(@PathVariable("id") Long id) {
        SysFileEntity file = fileService.getById(id);

        return R.ok().put("file", file);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("sys:file:save")
    public R save(@RequestBody SysFileEntity file) {
        fileService.save(file);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("sys:file:update")
    public R update(@RequestBody SysFileEntity file) {
        file.setUpdateDate(new Date());
        fileService.updateById(file);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("sys:file:delete")
    public R delete(@RequestBody Long[] ids) {
        fileService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @RequestMapping("upload")
    public R upload(@RequestParam(value = "file", required = true) MultipartFile file, String data) throws Exception {
        //类型校验
        String extentionRegex = "pdf|jpg|png";
        Pattern pattern = Pattern.compile(extentionRegex);
        String fileName = file.getOriginalFilename();
        String extention = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (!pattern.matcher(extention).matches()) {
            return R.error(-1, "文件类型有误：" + extention);
        }
        fileName = UUID.randomUUID() + "." + extention;
        //保存文件
        File destFile = FileUtils.createFileInDate(fileName);
        file.transferTo(destFile);
        SysFileEntity sysFileEntity = new SysFileEntity();
        sysFileEntity.setFileName(fileName);
        sysFileEntity.setFilePath(destFile.getPath());
        sysFileEntity.setFileType(extention);
        sysFileEntity.setFileSize((double) destFile.length());
        sysFileEntity.setFileStatus(1);
        sysFileEntity.setCreateDate(new Date());
        fileService.save(sysFileEntity);
        return R.ok("上传文件成功！").put("data", sysFileEntity.getId());
    }

}
